<template>
  <div>
    <!--搜索框-->
    <div class="pd-10">
      <el-input style="width: 200px" suffix-icon="el-icon-search" placeholder="请输入角色名称" class="mr-5" v-model="name"></el-input>
      <el-input style="width: 200px" suffix-icon="el-icon-message" placeholder="请输入角色描述" class="mr-5" v-model="description"></el-input>
      <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
    </div>
    <!--新增按钮-->
    <div class="mg-10">
      <el-button class="ml-5" type="primary" @click="handleAdd">
        <i class="el-icon-circle-plus-outline"></i>新增
      </el-button>
      <!--批量删除-->
      <el-popconfirm
          title="您确定批量删除这些数据吗？"
          @confirm="delBatch">
        <el-button class="ml-5" type="danger" slot="reference">
          <i class="el-icon-remove-outline"></i>批量删除
        </el-button>
      </el-popconfirm>
    </div>
    <el-table :data="tableData" border stripe :header-cell-style="{background: '#cccccc'}"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50">
      </el-table-column>
      <el-table-column prop="id" label="ID" width="50">
      </el-table-column>
      <el-table-column prop="name" label="名称">
      </el-table-column>
      <el-table-column prop="description" label="描述">
      </el-table-column>
      <el-table-column prop="flag" label="唯一标识">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="info" @click="selectMenu(scope.row)">分配菜单<i class="el-icon-menu"></i></el-button>
          <el-button type="success" @click="handleEdit(scope.row)">编辑<i class="el-icon-edit"></i></el-button>
          <el-popconfirm
              class="ml-5"
              confirm-button-text='确定'
              cancel-button-text='我再想想'
              icon="el-icon-info"
              icon-color="red"
              title="您确定删除吗？"
              @confirm="del(scope.row.id)">
            <el-button type="danger" slot="reference">删除<i class="el-icon-delete"></i></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    <!--新增编辑弹出框-->
    <el-dialog title="角色信息" :visible.sync="dialogFormVisible" width="30%">
      <el-form :model="form" size="small">
        <el-form-item label="角色名称" label-width="80px">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" label-width="80px">
          <el-input v-model="form.description" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="唯一标识" label-width="80px">
          <el-input v-model="form.flag" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
    <!--分配菜单弹出框-->
    <el-dialog title="分配菜单" :visible.sync="menuDialogFormVisible" width="30%">
      <!--树形结构-->
      <el-tree
          :data="menuData"
          :props="props"
          show-checkbox
          node-key="id"
          ref="tree"
          :default-expanded-keys="expands"
          :default-checked-keys="checks">
        <!--icon图标-->
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span><i :class="data.icon"></i>{{ data.name }}</span>
        </span>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleMenu">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Role",
  data() {
    return {
      tableData: [],
      menuData: [],
      name:"",
      path: "",
      description: "",
      form: {},
      dialogFormVisible: false,
      menuDialogFormVisible: false,
      multipleSelection: [],
      props: {
        label: "name"
      },
      //分页
      pageNum: 1,
      pageSize: 5,
      total: 0,
      expands: [],
      checks: [],
      roleId: 0,
      roleFlag: ""
    }
  },
  methods: {
    handleCheckChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate);
    },
    handleNodeClick(data) {
      console.log(data);
    },
    load() {
      this.request.get("/role/page",{
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name,
          path: this.path,
          description: this.description
        }
      }).then(res => {
        console.log(res);
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },
    handleAdd() {
      this.dialogFormVisible = true
    },
    save() {
      this.request.post("/role/save",this.form).then(res => {
        if (res.code === "200") {
          this.dialogFormVisible = false
          this.form = {}
          this.$message.success("保存成功")
          this.load()
        }else {
          this.$message.error("保存失败")
        }
      })
    },
    saveRoleMenu() {
      // console.log(this.$refs.tree.getCheckedNodes())
      // console.log(this.$refs.tree.getCheckedKeys())
      this.request.post("/role/roleMenu/" + this.roleId,this.$refs.tree.getCheckedKeys()).then(res => {
        if (res.code === "200") {
          this.menuDialogFormVisible = false
          //操作管理员角色后需要重新登录，操作其他用户不需要
          if (this.roleFlag === "ROLE_ADMIN") {
            //清缓存
            this.$store.commit("logout")
          }
          this.$message.success("绑定成功")
          // this.load()
        }else {
          this.$message.error("绑定失败")
        }
      })
    },
    handleEdit(row) {
      this.form = Object.assign({},row)
      this.dialogFormVisible = true
    },
    del(id) {
      this.request.delete("/role/"+id).then(res => {
        if (res.code === "200") {
          this.$message.success("删除成功")
          this.load()
        }else {
          this.$message.error("删除失败")
        }
      })
    },
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val
    },
    delBatch() {
      let ids = this.multipleSelection.map(v => v.id)
      this.request.post("/role/del/batch",ids).then(res => {
        if (res.code === "200") {
          this.$message.success("批量删除成功")
          this.load()
        }else {
          this.$message.error("批量删除失败")
        }
      })
    },
    reset() {
      this.name = ""
      this.load()
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.load()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val
      this.load()
    },
    selectMenu(role) {
      this.menuDialogFormVisible = true
      this.roleId = role.id
      this.roleFlag = role.flag
      //获取菜单数据
      this.request.get("/menu").then(res => {
        this.menuData = res.data
        this.expands = this.menuData.map(v => v.id)
      })
      //根据roleId获取已选菜单数据
      this.request.get("/role/roleMenu/" + this.roleId).then(res => {
        //解决方式一：先渲染弹窗中的元素，不然会报错 undefined
        // this.menuDialogFormVisible = true

        this.checks = res.data
        //获取所有的菜单id
        this.request.get("/menu/ids").then(r => {
          const ids = r.data
          //根据check数组里的id进行比较，如果出现不存在checks数组里的id就将它设置为false，也就是不选中
          ids.forEach(id => {
            if (!this.checks.includes(id)) {
              //解决方式二：使用$nextTick 处理未来元素，等到元素都渲染完成后，再去使用
              this.$nextTick(() => {
                this.$refs.tree.setChecked(id,false)
              })
            }
          })
          this.menuDialogFormVisible = true
        })
      })
    }
  },
  created() {
    this.load()
  },
  watch: {
    dialogFormVisible() {
      if (this.dialogFormVisible === false) {
        this.form = {}
        console.log("执行了watch方法")
      }
    }
  }

}
</script>

<style>
.el-header {
  color: #333;
  line-height: 60px;
}

.el-aside {
  color: #333;
}
</style>